#include "friendprofiletable.h"
#include "sqlitemanager.h"
#include "../profilemanager.h"
#include "../accountmanager.h"

#include <QDebug>
#include <QSqlQuery>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlRecord>

namespace Sqlite{
FriendProfileTable::FriendProfileTable(QObject *parent) :
    QObject(parent)
{
}

void FriendProfileTable::createTable()
{

    // create table
    QString str = "CREATE TABLE IF NOT EXISTS friendprofile (id INTEGER PRIMARY KEY,";
    str.append("username TEXT , ");
    str.append("displayName TEXT,");
    str.append("avatar TEXT,");
    str.append("avatarLocal TEXT,");
    str.append("senderMsg INTEGER,");// 0 : user id , 1 recieve message
    str.append("messageStatus TEXT,");
    str.append("time INTEGER,");
    str.append("typeMsg INTEGER,");//-1 errow, 0: message Status, 1 : message sent, reciev
    str.append("uid INTEGER ,");
    str.append("totalMember INTEGER )");

    QSqlQuery qry;
    qry.prepare(str );
    SqliteManager::instance()->doProcessSQLQuery(qry);
}

void FriendProfileTable::createTableFTS()
{
    // create table

    QString str = "CREATE VIRTUAL TABLE friendFTS USING fts3(content TEXT, uid INTEGER)";

    QSqlQuery qry;
    qry.prepare(str );
    SqliteManager::instance()->doProcessSQLQuery(qry);
}

QList<UserProfile*> FriendProfileTable::getAllFriendProfile()
{
    qDebug() << "FriendProfileTable::getAllFriendProfile() " ;

    qint64 uid  = AccountManager::instance()->getUserId();
    QSqlQuery qry;
    qry.prepare(QString("SELECT * FROM friendprofile where uid = %1 order by time DESC")
                .arg(uid));
    SqliteManager::instance()->doProcessSQLQuery(qry);
    qDebug() << qry.lastError();

    //    QSqlRecord rec = qry.record();
    //    int cols = rec.count();
    QList<UserProfile*> userProfiles;
    for( int r=0; qry.next(); r++ )
    {
        UserProfile* uProfile = new UserProfile();
        qint64 userId = qry.value(0).toInt();
        QString userName = qry.value(1).toString();
        QString displayName = qry.value(2).toString().trimmed();
        QString avatar = qry.value(3).toString();
        QString avatarLocal = qry.value(4).toString();
        int senderMsg = qry.value(5).toInt();
        QString messageStatus = qry.value(6).toString();
        qint64 time = qry.value(7).toLongLong();
        qint64 typeMsg = qry.value(8).toInt();
        int totalMember = qry.value(10).toInt();

        uProfile->setTime(time);
        uProfile->setSenderMsg(senderMsg);
        uProfile->setMessageStatus(messageStatus);
        uProfile->setTypeMsg(typeMsg);
        uProfile->setTotalMember(totalMember);

        uProfile->setBaseInfo(userId,userName, displayName, avatar);
        uProfile->setAvatarLocal(avatarLocal);

        userProfiles.push_back(uProfile);

    }

    return userProfiles;

}

QList<UserProfile*> FriendProfileTable::refreshListFriends()
{
    qint64 uid  = AccountManager::instance()->getUserId();
    QString command = QString("SELECT * FROM friendprofile where uid = %1 order by time DESC").arg(uid);

    QSqlQuery qry;
    qry.prepare( command);
    SqliteManager::instance()->doProcessSQLQuery(qry);
    qDebug() << qry.lastError();


    QList<UserProfile*> userProfiles;
    for( int r=0; qry.next(); r++ )
    {
        qint64 userId = qry.value(0).toInt();
        UserProfile* uProfile = ProfileManager::instance()->getProfileById(userId);

        userProfiles.push_back(uProfile);
        qDebug()<< "*****************************************" <<userId;
    }
    return userProfiles;

}

//SELECT id, displayName, upper(substr(trim(displayName, " "), 0,2))  as firstChar   FROM friendprofile where uid = 31166118 order by firstChar  ASC
QList<UserProfile*> FriendProfileTable::friendListSortByName()
{
    qint64 uid  = AccountManager::instance()->getUserId();
    QString str = QString("");
    str.append("SELECT");
    str.append(" id,");
    str.append(" displayName,");
    str.append(" upper(substr(trim(displayName, \" \"), 0,2))  as firstChar ");
    str.append(" FROM friendprofile");
    str.append(" where uid = %1 ");
    str.append(" order by firstChar, displayName  ASC");


    QString command = QString(str).arg(uid);

    QSqlQuery qry;
    qry.prepare( command);
    SqliteManager::instance()->doProcessSQLQuery(qry);
    qDebug() << qry.lastError();


    QList<UserProfile*> userProfiles;
    for( int r=0; qry.next(); r++ )
    {
        qint64 userId = qry.value(0).toInt();
        UserProfile* uProfile = ProfileManager::instance()->getProfileById(userId);

        //userProfiles.push_back(uProfile);

        userProfiles.append(uProfile);
    }
    return userProfiles;
}

QList<UserProfile*> FriendProfileTable::searchFriendsFTS(QString input)
{
    qint64 uid  = AccountManager::instance()->getUserId();
    QString command = QString("SELECT friendprofile.id FROM friendFTS, friendprofile WHERE content  MATCH '*%1*' and friendFTS.docid = friendprofile.id and friendFTS.uid = %2 ;")
            .arg(input)
            .arg(uid);

    QSqlQuery qry;
    qry.prepare( command);
    SqliteManager::instance()->doProcessSQLQuery(qry);
    qDebug() << qry.lastError();


    QList<UserProfile*> userProfiles;
    for( int r=0; qry.next(); r++ )
    {
        qint64 userId = qry.value(0).toInt();
        UserProfile* uProfile = ProfileManager::instance()->getProfileById(userId);

        userProfiles.push_back(uProfile);
    }
    return userProfiles;


    QList<UserProfile*> ret ;
    UserProfile* uProfile = new UserProfile();
    ret.push_back(uProfile);
    return ret;

}

void FriendProfileTable::updateMessageStatus(const qint64 friendId,
                                             const int senderMsg,
                                             const QString msgStatus,
                                             const qint64 time,
                                             const int typeMsg)
{
    QString command = QString("UPDATE  friendprofile  SET  senderMsg = %1 , messageStatus = '%2', time = %3, typeMsg = %4 where id = %5")
            .arg(senderMsg)
            .arg(msgStatus)
            .arg(time)
            .arg(typeMsg)
            .arg(friendId);
    QSqlQuery qry;
    qry.prepare(command);
    SqliteManager::instance()->doProcessSQLQuery(qry);
}

void FriendProfileTable::addFriendProfile(const UserProfile *fProfile)
{
    qint64 uid  = AccountManager::instance()->getUserId();
    QString str = QString("INSERT OR REPLACE INTO friendprofile (id, username, displayName, avatar, avatarLocal, senderMsg, messageStatus, time, typeMsg, uid, totalMember) VALUES (%1, '%2','%3', '%4', '%5', %6 , '%7', %8, %9, %10, %11)")
            .arg(fProfile->getUserId())
            .arg(fProfile->getUserName())
            .arg(fProfile->getDisplayName())
            .arg(fProfile->getAvatar())
            .arg(fProfile->getAvatarLocal())
            .arg(-1)
            .arg(QString(""))
            .arg(-1)
            .arg(-1)
            .arg(uid)
            .arg(fProfile->getTotalMember());

    QSqlQuery qry;
    qry.prepare(str);
    SqliteManager::instance()->doProcessSQLQuery(qry);

}

void FriendProfileTable::addFriendProfileFTS(const UserProfile *fProfile)
{
    QString content;
    content.append(fProfile->getDisplayName());
    content.append(" ");
    content.append(fProfile->getDisplayName().toLower());
    content.append(" ");
    content.append(fProfile->getDisplayName().toUpper());
    content.append(" ");
    content.append(fProfile->getUserName());
    content.append(" ");
    content.append(fProfile->getUserName().toLower());
    content.append(" ");
    content.append(fProfile->getUserName().toUpper());

    QString str = QString("INSERT OR REPLACE INTO friendFTS (docid, content, uid) VALUES (%1, '%2', %3)").
            arg(fProfile->getUserId())
            .arg(content)
            .arg(AccountManager::instance()->getUserId());

    QSqlQuery qry;
    qry.prepare(str);
    SqliteManager::instance()->doProcessSQLQuery(qry);

    qDebug() << "FriendProfileTable::addFriendProfileFTS()==============";

}

void FriendProfileTable::clearTable()
{
    QSqlQuery qry;
    QString strdeleteAll("delete from friendprofile");
    qry.prepare(strdeleteAll);
    SqliteManager::instance()->doProcessSQLQuery(qry);
}

void FriendProfileTable::clearTableFTS()
{
    //m_mapListFriends.clear();

    QSqlQuery qry;
    QString strdeleteAll("delete from friendFTS");
    qry.prepare(strdeleteAll);
    SqliteManager::instance()->doProcessSQLQuery(qry);
}

}
